package com.jy.rhin.infra.repo.document.submission.query;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jy.framework.base.entity.Page;
import com.jy.framework.base.utils.Converter;
import com.jy.rhin.domain.document.submission.entity.DocumentEntryVO;
import com.jy.rhin.domain.document.submission.entity.DocumentFolderVO;
import com.jy.rhin.domain.document.submission.entity.DocumentSubmissionDO;
import com.jy.rhin.domain.exception.RhinInfraErrorType;
import com.jy.rhin.facade.dto.DocumentManagerDTO;
import com.jy.rhin.infra.repo.document.submission.mapper.DocumentAssociationMapper;
import com.jy.rhin.infra.repo.document.submission.mapper.DocumentEntryMapper;
import com.jy.rhin.infra.repo.document.submission.mapper.DocumentFolderMapper;
import com.jy.rhin.infra.repo.document.submission.mapper.DocumentSubmissionSetMapper;
import com.jy.rhin.infra.repo.document.submission.po.DocumentAssociationPO;
import com.jy.rhin.infra.repo.document.submission.po.DocumentEntryPO;
import com.jy.rhin.infra.repo.document.submission.po.DocumentFolderPO;
import com.jy.rhin.infra.repo.document.submission.po.DocumentSubmissionSetPO;
import com.jy.rhin.infra.uitl.Asserts;
import com.jy.rhin.sdk.dto.document.*;
import com.jy.rhin.sdk.dto.document.query.*;
import com.jy.starter.repository.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.jy.rhin.infra.uitl.LambdaPropertyUtils.getClassFieldName;

/**
 * @author dhl
 * @date 2022/6/1
 * @Description
 */
@Slf4j
@Service
public class DocumentSubmissionQueryHandler {

    private static final String CARD_TYPE = "身份证";
    private static final String MAX_TIME = " 23:59:59";
    private static final String SUBMISSION_TIME = "a.submission_time";
    private static final String HOME_COMMUNITY_ID = "b.home_community_id";
    private static final String LAST_UPDATE_TIME = "a.last_update_time";
    private static final String UNIQUE_ID = "b.unique_id";
    @Resource
    private DocumentEntryMapper documentEntryMapper;
    @Resource
    private DocumentFolderMapper documentFolderMapper;
    @Resource
    private DocumentAssociationMapper documentAssociationMapper;
    @Resource
    private DocumentSubmissionSetMapper documentSubmissionSetMapper;

    /**
     * C.2.2 查询文档提交集（FindSubmissionSets）
     */
    public DocumentResultDto<DocumentSubmissionSetDto> findSubmissionSets(FindSubmissionSetsDto dto) {
        checkIdValue(dto.getId());
        Map<String, List<String>> codingTableQueryParamMap = new HashMap<>();
        //当由coding表需要参与查询时 组装值列表
        if (!CollectionUtils.isEmpty(dto.getContentTypeCodeList())) {
            codingTableQueryParamMap.put(getClassFieldName(DocumentSubmissionDO.class, DocumentSubmissionDO::getContentTypeCode), dto.getContentTypeCodeList());
        }

        QueryWrapper<DocumentSubmissionSetPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(dto.getId()), "a.id", Long.parseLong(dto.getId()))
                .in(!CollectionUtils.isEmpty(dto.getSourceIdList()), "a.source_id", dto.getSourceIdList())
                .func(!CollectionUtils.isEmpty(codingTableQueryParamMap), wrapper -> wrapper.inSql("a.id", queryCodingSql(codingTableQueryParamMap)))
                .func(!ObjectUtils.isEmpty(dto.getSubmissionTimeStart()), wrapper -> wrapper.ge(SUBMISSION_TIME, dto.getSubmissionTimeStart()))
                .func(!ObjectUtils.isEmpty(dto.getSubmissionTimeEnd()), wrapper -> wrapper.le(SUBMISSION_TIME, getEndDateTime(dto.getSubmissionTimeEnd())))
                .orderByDesc(SUBMISSION_TIME);
        List<DocumentSubmissionSetPO> poList = documentSubmissionSetMapper.querySubmissionSetListByCoding(queryWrapper);
        return convert(poList, po -> toDto(po, DocumentSubmissionSetDto.class));
    }

    /**
     * C.2.7 获取文档提交集（GetSubmissionSets）
     */
    public DocumentResultDto<DocumentSubmissionSetDto> getSubmissionSets(GetSubmissionSetsDto dto) {

        QueryWrapper<DocumentSubmissionSetPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(dto.getHomeCommunityId()), HOME_COMMUNITY_ID, dto.getHomeCommunityId())
                .in(!CollectionUtils.isEmpty(dto.getIdList()), "b.id", dto.getIdList())
                .orderByDesc(SUBMISSION_TIME);
        List<DocumentSubmissionSetPO> poList = documentSubmissionSetMapper.querySubmissionSetListByEntry(queryWrapper);
        return convert(poList, po -> toDto(po, DocumentSubmissionSetDto.class));
    }

    /**
     * C.2.8 获取文档提交集及内容(GetSubmissionSetAndContents
     */
    public DocumentResultDto<DocumentSubmissionSetDto> getSubmissionSetAndContents(GetSubmissionSetAndContentsDto dto) {
        checkIdValue(dto.getId());

        //当由coding表需要参与查询时 组装值列表
        Map<String, List<String>> codingTableQueryParamMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(dto.getConfidentialityCodeList())) {
            codingTableQueryParamMap.put(getClassFieldName(DocumentEntryVO.class, DocumentEntryVO::getConfidentialityCode), dto.getConfidentialityCodeList());
        }

        QueryWrapper<DocumentSubmissionSetPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(dto.getId()), "a.id", dto.getId())
                .eq(StringUtils.isNotEmpty(dto.getUniqueId()), "a.unique_id", dto.getUniqueId())
                .eq(StringUtils.isNotEmpty(dto.getHomeCommunityId()), HOME_COMMUNITY_ID, dto.getHomeCommunityId())
                .in(!CollectionUtils.isEmpty(dto.getFormatCodeList()), "b.format_code", dto.getFormatCodeList())
                .func(!CollectionUtils.isEmpty(codingTableQueryParamMap), wrapper -> wrapper.inSql("b.id", queryCodingSql(codingTableQueryParamMap)))
                .orderByDesc(SUBMISSION_TIME);
        List<DocumentSubmissionSetPO> poList = documentSubmissionSetMapper.querySubmissionSetListByEntry(queryWrapper);
        return convert(poList, po -> toDto(po, DocumentSubmissionSetDto.class));
    }


    /**
     * C.2.1 查询文档（FindDocuments）
     */
    public DocumentResultDto<DocumentEntryDto> findDocuments(FindDocumentsDto dto) {

        //当由coding表需要参与查询时 组装值列表
        Map<String, List<String>> codingTableQueryParamMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(dto.getClassCodeList())) {
            codingTableQueryParamMap.put(getClassFieldName(DocumentEntryVO.class, DocumentEntryVO::getClassCode), dto.getClassCodeList());
        }
        if (!CollectionUtils.isEmpty(dto.getTypeCodeList())) {
            codingTableQueryParamMap.put(getClassFieldName(DocumentEntryVO.class, DocumentEntryVO::getTypeCode), dto.getTypeCodeList());
        }
        if (!CollectionUtils.isEmpty(dto.getEventCodeList())) {
            codingTableQueryParamMap.put(getClassFieldName(DocumentEntryVO.class, DocumentEntryVO::getEventCode), dto.getEventCodeList());
        }
        if (!CollectionUtils.isEmpty(dto.getConfidentialityCodeList())) {
            codingTableQueryParamMap.put(getClassFieldName(DocumentEntryVO.class, DocumentEntryVO::getConfidentialityCode), dto.getConfidentialityCodeList());
        }
        if (!CollectionUtils.isEmpty(dto.getPracticeSettingCodeList())) {
            codingTableQueryParamMap.put(getClassFieldName(DocumentEntryVO.class, DocumentEntryVO::getPracticeSettingCode), dto.getPracticeSettingCodeList());
        }
        if (!CollectionUtils.isEmpty(dto.getHealthcareFacilityTypeCodeList())) {
            codingTableQueryParamMap.put(getClassFieldName(DocumentEntryVO.class, DocumentEntryVO::getHealthcareFacilityTypeCode), dto.getHealthcareFacilityTypeCodeList());
        }

        QueryWrapper<DocumentEntryPO> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .in(!CollectionUtils.isEmpty(dto.getStatusCodeList()), "a.status_code", dto.getStatusCodeList())
                .in(!CollectionUtils.isEmpty(dto.getFormatCodeList()), "a.format_code", dto.getFormatCodeList())
                .func(!ObjectUtils.isEmpty(dto.getCreationTimeStart()), wrapper -> wrapper.ge("a.creation_time", dto.getCreationTimeStart()))
                .func(!ObjectUtils.isEmpty(dto.getCreationTimeEnd()), wrapper -> wrapper.le("a.creation_time", getEndDateTime(dto.getCreationTimeEnd())))
                .func(!ObjectUtils.isEmpty(dto.getServiceStartTimeStart()), wrapper -> wrapper.ge("a.service_start_time", dto.getServiceStartTimeStart()))
                .func(!ObjectUtils.isEmpty(dto.getServiceStartTimeEnd()), wrapper -> wrapper.le("a.service_start_time", getEndDateTime(dto.getServiceStartTimeEnd())))
                .func(!ObjectUtils.isEmpty(dto.getServiceStopTimeStart()), wrapper -> wrapper.ge("a.service_stop_time", dto.getServiceStopTimeStart()))
                .func(!ObjectUtils.isEmpty(dto.getServiceStopTimeEnd()), wrapper -> wrapper.le("a.service_stop_time", getEndDateTime(dto.getServiceStopTimeEnd())))
                .eq(StringUtils.isNotEmpty(dto.getPatientId()), "a.patient_id", dto.getPatientId())
                .func(!CollectionUtils.isEmpty(codingTableQueryParamMap), wrapper -> wrapper.inSql("a.id", queryCodingSql(codingTableQueryParamMap)));
        List<DocumentEntryPO> poList = documentEntryMapper.queryDocumentEntryListByCoding(queryWrapper);
        return convert(poList, po -> toDto(po, DocumentEntryDto.class), DocumentEntryPO::getSubmissionId);
    }

    /**
     * C.2.4 获取文档（GetDocuments）
     */
    public DocumentResultDto<DocumentEntryDto> getDocuments(GetDocumentsDto dto) {
        QueryWrapper<DocumentEntryPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(StringUtils.isNotEmpty(dto.getHomeCommunityId()), DocumentEntryPO::getHomeCommunityId, dto.getHomeCommunityId())
                .in(!CollectionUtils.isEmpty(dto.getIdList()), DocumentEntryPO::getId, dto.getIdList())
                .in(!CollectionUtils.isEmpty(dto.getUniqueIdList()), DocumentEntryPO::getUniqueId, dto.getUniqueIdList());
        List<DocumentEntryPO> poList = documentEntryMapper.selectList(queryWrapper);
        return convert(poList, po -> toDto(po, DocumentEntryDto.class), DocumentEntryPO::getSubmissionId);
    }

    /**
     * C.2.3 查询文件夹（FindFolders）
     */
    public DocumentResultDto<DocumentFolderDto> findFolders(FindFoldersDto dto) {

        //当由coding表需要参与查询时 组装值列表
        Map<String, List<String>> codingTableQueryParamMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(dto.getTypeCodeList())) {
            codingTableQueryParamMap.put(getClassFieldName(DocumentFolderVO.class, DocumentFolderVO::getTypeCode), dto.getTypeCodeList());
        }

        QueryWrapper<DocumentFolderPO> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq(StringUtils.isNotEmpty(dto.getPatientId()), "a.patient_id", dto.getPatientId())
                .in(!CollectionUtils.isEmpty(dto.getStatusCodeList()), "a.status_code", dto.getStatusCodeList())
                .func(!ObjectUtils.isEmpty(dto.getLastUpdateTimeStart()), wrapper -> wrapper.ge(LAST_UPDATE_TIME, dto.getLastUpdateTimeStart()))
                .func(!ObjectUtils.isEmpty(dto.getLastUpdateTimeEnd()), wrapper -> wrapper.le(LAST_UPDATE_TIME, getEndDateTime(dto.getLastUpdateTimeEnd())))
                .func(!CollectionUtils.isEmpty(codingTableQueryParamMap), wrapper -> wrapper.inSql("a.id", queryCodingSql(codingTableQueryParamMap)))
                .orderByDesc(LAST_UPDATE_TIME);
        List<DocumentFolderPO> poList = documentFolderMapper.queryDocumengFolderListByCoding(queryWrapper);
        return convert(poList, po -> toDto(po, DocumentFolderDto.class), DocumentFolderPO::getSubmissionId);
    }

    /**
     * C.2.5 获取文件夹（GetFolders）
     */
    public DocumentResultDto<DocumentFolderDto> getFolders(GetFoldersDto dto) {

        QueryWrapper<DocumentFolderPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(StringUtils.isNotEmpty(dto.getHomeCommunityId()), DocumentFolderPO::getHomeCommunityId, dto.getHomeCommunityId())
                .in(!CollectionUtils.isEmpty(dto.getIdList()), DocumentFolderPO::getId, dto.getIdList())
                .in(!CollectionUtils.isEmpty(dto.getUniqueIdList()), DocumentFolderPO::getUniqueId, dto.getUniqueIdList())
                .orderByDesc(DocumentFolderPO::getLastUpdateTime);
        List<DocumentFolderPO> poList = documentFolderMapper.selectList(queryWrapper);
        return convert(poList, po -> toDto(po, DocumentFolderDto.class), DocumentFolderPO::getSubmissionId);
    }

    /**
     * C.2.9 获取文件夹及内容
     */
    public DocumentResultDto<DocumentFolderDto> getFolderAndContents(GetFolderAndContentsDto dto) {
        checkIdValue(dto.getId());

        //当由coding表需要参与查询时 组装值列表
        Map<String, List<String>> codingTableQueryParamMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(dto.getConfidentialityCodeList())) {
            codingTableQueryParamMap.put(getClassFieldName(DocumentEntryVO.class, DocumentEntryVO::getConfidentialityCode), dto.getConfidentialityCodeList());
        }

        QueryWrapper<DocumentFolderPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(dto.getId()), "a.id", dto.getId())
                .eq(StringUtils.isNotEmpty(dto.getUniqueId()), "a.unique_id", dto.getUniqueId())
                .eq(StringUtils.isNotEmpty(dto.getHomeCommunityId()), HOME_COMMUNITY_ID, dto.getHomeCommunityId())
                .in(!CollectionUtils.isEmpty(dto.getFormatCodeList()), "b.format_code", dto.getFormatCodeList())
                .func(!CollectionUtils.isEmpty(codingTableQueryParamMap), wrapper -> wrapper.inSql("b.id", queryCodingSql(codingTableQueryParamMap)))
                .orderByDesc(LAST_UPDATE_TIME);
        List<DocumentFolderPO> poList = documentFolderMapper.queryDocumentFolderListByEntry(queryWrapper);
        return convert(poList, po -> toDto(po, DocumentFolderDto.class), DocumentFolderPO::getSubmissionId);
    }

    /**
     * C.2.10 获取文档相关文件夹
     */
    public DocumentResultDto<DocumentFolderDto> getFoldersForDocument(GetFoldersForDocumentDto dto) {

        QueryWrapper<DocumentFolderPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(dto.getId()), "b.id", dto.getId())
                .eq(StringUtils.isNotEmpty(dto.getUniqueId()), UNIQUE_ID, dto.getUniqueId())
                .eq(StringUtils.isNotEmpty(dto.getHomeCommunityId()), HOME_COMMUNITY_ID, dto.getHomeCommunityId())
                .orderByDesc(LAST_UPDATE_TIME);
        List<DocumentFolderPO> poList = documentFolderMapper.queryDocumentFolderListByEntry(queryWrapper);
        return convert(poList, po -> toDto(po, DocumentFolderDto.class), DocumentFolderPO::getSubmissionId);
    }

    /**
     * C.2.6 获取文档以及文档的关联关系（GetDocumentAndAssociations）
     */
    public DocumentResultDto<DocumentAssociationDto> getDocumentAndAssociations(GetDocumentAndAssociationsDto dto) {

        QueryWrapper<DocumentAssociationPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(dto.getId()), "b.id", dto.getId())
                .eq(StringUtils.isNotEmpty(dto.getUniqueId()), UNIQUE_ID, dto.getUniqueId())
                .eq(StringUtils.isNotEmpty(dto.getHomeCommunityId()), HOME_COMMUNITY_ID, dto.getHomeCommunityId())
                .orderByDesc("b.creation_time");
        List<DocumentAssociationPO> poList = documentAssociationMapper.queryDocumentAssociationListByEntry(queryWrapper);
        return convert(poList, po -> toDto(po, DocumentAssociationDto.class), DocumentAssociationPO::getSubmissionId);
    }

    /**
     * C.2.11 获取关联文档
     */
    public DocumentResultDto<DocumentAssociationDto> getRelatedDocuments(GetRelatedDocumentsDto dto) {

        QueryWrapper<DocumentAssociationPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(dto.getId()), "b.id", dto.getId())
                .eq(StringUtils.isNotEmpty(dto.getUniqueId()), UNIQUE_ID, dto.getUniqueId())
                .eq(StringUtils.isNotEmpty(dto.getHomeCommunityId()), HOME_COMMUNITY_ID, dto.getHomeCommunityId())
                .in(!CollectionUtils.isEmpty(dto.getTypeCodeList()), "a.type_code", dto.getTypeCodeList())
                .orderByDesc("b.creation_time");
        List<DocumentAssociationPO> poList = documentAssociationMapper.queryDocumentAssociationListByEntry(queryWrapper);
        return convert(poList, po -> toDto(po, DocumentAssociationDto.class), DocumentAssociationPO::getSubmissionId);
    }

    /**
     * 文档管理分页查询
     */
    public Page<DocumentManagerRespDto> getDocumentManagerPage(DocumentManagerReqDto dto) {

        QueryWrapper<DocumentEntryPO> entryQueryWrapper = new QueryWrapper<>();
        entryQueryWrapper.lambda()
                .eq(!StringUtils.isEmpty(dto.getOrgId()), DocumentEntryPO::getOrgId, dto.getOrgId())
                .and(!StringUtils.isEmpty(dto.getQueryText()), wrapper -> wrapper.or().like(DocumentEntryPO::getHuanZheXm, dto.getQueryText())
                        .or().like(DocumentEntryPO::getZhengJianHm, dto.getQueryText()))
                .func(!StringUtils.isEmpty(dto.getKaiShiRQ()), wrapper -> wrapper.ge(DocumentEntryPO::getCreationTime, Converter.toDate(dto.getKaiShiRQ(), Converter.DATE_FORMAT)))
                .func(!StringUtils.isEmpty(dto.getJieShuRQ()), wrapper -> wrapper.le(DocumentEntryPO::getCreationTime, Converter.toDate(dto.getJieShuRQ() + MAX_TIME, Converter.DATETIME_FORMAT)))
                .func(!StringUtils.isEmpty(dto.getClassCode()), wrapper -> wrapper.inSql(DocumentEntryPO::getId, queryEntryCodingSql(getClassFieldName(DocumentEntryVO.class, DocumentEntryVO::getClassCode), dto.getClassCode())))
                .func(!StringUtils.isEmpty(dto.getTypeCode()), wrapper -> wrapper.inSql(DocumentEntryPO::getId, queryEntryCodingSql(getClassFieldName(DocumentEntryVO.class, DocumentEntryVO::getTypeCode), dto.getTypeCode())))
                .orderByDesc(DocumentEntryPO::getCreationTime);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<DocumentEntryPO> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(dto.getPageNo(), dto.getPageSize(), true);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<DocumentEntryPO> selectResult = documentEntryMapper.selectPage(page, entryQueryWrapper);
        return PageUtils.page(selectResult, this::toDto);
    }

    public Page<DocumentManagerDTO> getDocumentManagerPageNew(DocumentManagerReqDto dto) {
        QueryWrapper<DocumentEntryPO> entryQueryWrapper = new QueryWrapper<>();
        entryQueryWrapper.lambda()
                .eq(!StringUtils.isEmpty(dto.getOrgId()), DocumentEntryPO::getOrgId, dto.getOrgId())
                .and(!StringUtils.isEmpty(dto.getQueryText()), wrapper -> wrapper.or().like(DocumentEntryPO::getHuanZheXm, dto.getQueryText())
                        .or().like(DocumentEntryPO::getZhengJianHm, dto.getQueryText()))
                .func(!StringUtils.isEmpty(dto.getKaiShiRQ()), wrapper -> wrapper.ge(DocumentEntryPO::getCreationTime, Converter.toDate(dto.getKaiShiRQ(), Converter.DATE_FORMAT)))
                .func(!StringUtils.isEmpty(dto.getJieShuRQ()), wrapper -> wrapper.le(DocumentEntryPO::getCreationTime, Converter.toDate(dto.getJieShuRQ() + MAX_TIME, Converter.DATETIME_FORMAT)))
                .func(!StringUtils.isEmpty(dto.getClassCode()), wrapper -> wrapper.inSql(DocumentEntryPO::getId, queryEntryCodingSql(getClassFieldName(DocumentEntryVO.class, DocumentEntryVO::getClassCode), dto.getClassCode())))
                .func(!StringUtils.isEmpty(dto.getTypeCode()), wrapper -> wrapper.inSql(DocumentEntryPO::getId, queryEntryCodingSql(getClassFieldName(DocumentEntryVO.class, DocumentEntryVO::getTypeCode), dto.getTypeCode())))
                .orderByDesc(DocumentEntryPO::getCreationTime);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<DocumentEntryPO> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(dto.getPageNo(), dto.getPageSize(), true);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<DocumentEntryPO> selectResult = documentEntryMapper.selectPage(page, entryQueryWrapper);
        return PageUtils.page(selectResult, this::toConvert);
    }

    private DocumentManagerRespDto toDto(DocumentEntryPO po) {
        DocumentManagerRespDto respDto = new DocumentManagerRespDto();
        BeanUtils.copyProperties(po, respDto);
        respDto.setZhengJianLx(CARD_TYPE);
        return respDto;
    }

    private DocumentManagerDTO toConvert(DocumentEntryPO po) {
        DocumentManagerDTO respDto = new DocumentManagerDTO();
        BeanUtils.copyProperties(po, respDto);
        respDto.setZhengJianLx(CARD_TYPE);
        return respDto;
    }

    /**
     * 获取文档提交集元jsonText内容
     *
     * @param submissionSetId
     * @return
     */
    public String querySubmissionSetJsonText(Long submissionSetId) {
        DocumentSubmissionSetPO po = documentSubmissionSetMapper.selectById(submissionSetId);
        if (Objects.nonNull(po)) {
            return po.getJsonText();
        }
        return "";
    }

    /**
     * 根据提交集id获取文档元相关jsonText列表
     *
     * @param submissionSetId
     * @return
     */
    public List<String> queryEntryJsonTextListBySubmissionSetId(Long submissionSetId) {
        QueryWrapper<DocumentEntryPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DocumentEntryPO::getSubmissionId, submissionSetId)
                .orderByAsc(DocumentEntryPO::getCreationTime);
        List<DocumentEntryPO> poList = documentEntryMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(poList)) {
            return poList.stream().map(DocumentEntryPO::getJsonText).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 校验id内容可以转long
     */
    private void checkIdValue(String id) {
        Asserts.isNumber(id, RhinInfraErrorType.METHOD_NAME_ERROR);
    }

    /**
     * po转dto
     */
    private <T> T toDto(Object po, Class<T> dtoClass) {
        try {
            T dto = dtoClass.newInstance();
            BeanUtils.copyProperties(po, dto);
            return dto;
        } catch (Exception e) {
            log.error("dto转化异常", ExceptionUtils.getFullStackTrace(e));
            return null;
        }

    }

    /**
     * 非文档提交集元素结果转换
     */
    private <P, T> DocumentResultDto<T> convert(List<P> poList, Function<P, T> mapper, Function<P, Long> submissionIdGetter) {
        if (CollectionUtils.isEmpty(poList)) {
            return new DocumentResultDto<>();
        }

        Set<Long> submissionIdList = poList.stream().map(submissionIdGetter).collect(Collectors.toSet());
        List<String> jsonTextList = querySubmissionSetJsonTextList(submissionIdList).stream().map(DocumentSubmissionSetPO::getJsonText).collect(Collectors.toList());
        List<T> collect = poList.stream().map(mapper).collect(Collectors.toList());
        return new DocumentResultDto<>(jsonTextList, collect);
    }

    /**
     * 文档提交集元素结果转换
     */
    private <T> DocumentResultDto<T> convert(List<DocumentSubmissionSetPO> poList, Function<DocumentSubmissionSetPO, T> mapper) {
        if (CollectionUtils.isEmpty(poList)) {
            return new DocumentResultDto<>();
        }
        List<String> jsonTextList = poList.stream().map(DocumentSubmissionSetPO::getJsonText).collect(Collectors.toList());
        List<T> collect = poList.stream().map(mapper).collect(Collectors.toList());
        return new DocumentResultDto<>(jsonTextList, collect);
    }


    /**
     * 根据提交集id列表获取数据列表
     */
    private List<DocumentSubmissionSetPO> querySubmissionSetJsonTextList(Set<Long> submissionIdList) {
        QueryWrapper<DocumentSubmissionSetPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .in(DocumentSubmissionSetPO::getId, submissionIdList)
                .orderByDesc(DocumentSubmissionSetPO::getSubmissionTime);
        return documentSubmissionSetMapper.selectList(queryWrapper);
    }

    /**
     * 组装coding查询的sql语句
     * 输出结果 select x.module_id from t_rhin_coding x WHERE (x.module, x.code_value) IN (('key1','v1-1'),('key1','v1-2'),('key2','v2-1'),('key2','v2-2'),('key3','v3-1'),('key3','v3-2'))
     */
    private static String queryCodingSql(Map<String, List<String>> codingTableQueryParamMap) {
        StringBuilder sqlBuilder = new StringBuilder(" select distinct x.module_id from t_rhin_coding x WHERE (x.module, x.code_value) IN (");
        codingTableQueryParamMap.forEach((key, valueList) -> valueList.forEach(value -> sqlBuilder.append("('").append(key).append("','").append(value).append("'),")));
        sqlBuilder.setCharAt(sqlBuilder.length() - 1, ')');
        return sqlBuilder.toString();
    }

    /**
     * 文档管理分页查询独立的条件查询拼接
     *
     * @param moduleName
     * @param value
     * @return
     */
    private String queryEntryCodingSql(String moduleName, String value) {
        return " select distinct x.module_id from t_rhin_coding x WHERE " + " x.module = '" + moduleName + "' and x.code_value = '" + value + "' ";
    }

    /**
     * yyyy-MM-dd 转 yyyy-MM-dd 23:59:59
     */
    private Date getEndDateTime(Date date) {
        return Converter.toDate(DateFormatUtils.format(date, Converter.DATE_FORMAT) + MAX_TIME, Converter.DATETIME_FORMAT);
    }


}
